package com.yfuxdeer.youchat.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yfuxdeer.youchat.R;
import com.yfuxdeer.youchat.service.ClientService;
import com.yfuxdeer.youchat.pojo.User;
import com.yfuxdeer.youchat.service.UserService;
import com.yfuxdeer.youchat.ui.fragment.ListFragment;
import com.yfuxdeer.youchat.ui.fragment.MomentFragment;
import com.yfuxdeer.youchat.utils.ImageUtil;
import com.yfuxdeer.youchat.utils.Store;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ImageButton messageBtn;
    private ImageButton friendBtn;
    private ImageButton momentBtn;
    private ImageButton drawerBtn;
    private ImageView headImage;
    private ImageView profile_headImage;
    private TextView profile_NickName;
    private TextView nickName;
    private TextView profile_figure;
    private Button profile_logout;
    private Button profile_about;
    private Button add_friend;
    private Button publish_moment;
    private Button profile_celar_cache;
    private DrawerLayout drawerLayout;
    private Store store = Store.getInstance();
    public static boolean flush = false;
    private boolean net_state = true;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true); //添加到后台执行
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop: ");
        if (flush) {
            ImageUtil.clearImageAllCache(getApplicationContext());
            flush = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e(TAG, "onCreate: ");
        //注册广播
        registerReceiver(clearCacheReceiver, new IntentFilter("com.yfuxdeer.youchat.clearCacheReceiver"));
        registerReceiver(updateUserReceiver, new IntentFilter("com.yfuxdeer.youchat.updateUserReceiver"));
        registerReceiver(netChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        findViews();
        setListeners();
        initClient();
        initPages();
        switchMessageFragment();
    }

    private void switchMessageFragment() {
        messageBtn.setImageDrawable(getDrawable(R.drawable.bottom_1));
        friendBtn.setImageDrawable(getDrawable(R.drawable.bottom2));
        momentBtn.setImageDrawable(getDrawable(R.drawable.bottom3));

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ListFragment messageItemFragment = ListFragment.newInstance();
        messageItemFragment.setType(ListFragment.MESSAGE_ITEM);
        fragmentTransaction.replace(R.id.will_be_replaced, messageItemFragment);
        fragmentTransaction.commit();
    }

    private void switchFriendFragment() {
        messageBtn.setImageDrawable(getDrawable(R.drawable.bottom1));
        friendBtn.setImageDrawable(getDrawable(R.drawable.bottom_2));
        momentBtn.setImageDrawable(getDrawable(R.drawable.bottom3));

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        ListFragment friendItemFragment = ListFragment.newInstance();
        friendItemFragment.setType(ListFragment.FRIEND_ITEM);
        fragmentTransaction.replace(R.id.will_be_replaced, friendItemFragment);
        fragmentTransaction.commit();
    }

    private void switchMomentFragment() {
        messageBtn.setImageDrawable(getDrawable(R.drawable.bottom1));
        friendBtn.setImageDrawable(getDrawable(R.drawable.bottom2));
        momentBtn.setImageDrawable(getDrawable(R.drawable.bottom_3));

        FragmentManager fragmentManager = this.getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        MomentFragment momentItemFragment = MomentFragment.newInstance();
        fragmentTransaction.replace(R.id.will_be_replaced, momentItemFragment);
        fragmentTransaction.commit();
    }

    private void initPages() {
        Log.e(TAG, "initPages: ");
        ImageUtil.glideLoad(getApplicationContext(), store.getCurrentUser().getUsername(), store.cacheState, headImage);
        //初始化个人信息及抽屉
        nickName.setText(store.getCurrentUser().getNickName());
        ImageUtil.glideLoad(getApplicationContext(), store.getCurrentUser().getUsername(), store.cacheState, profile_headImage);
        profile_NickName.setText(store.getCurrentUser().getNickName());
        profile_figure.setText(store.getCurrentUser().getFigure());
    }

    private void initClient() {

        //开启客户端
        Log.e(TAG, "initClient: " + "启动了连接Socket服务");
        Intent clientService = new Intent(getApplicationContext(), ClientService.class);
        startService(clientService);

    }

    private void findViews() {
        messageBtn = findViewById(R.id.message);
        friendBtn = findViewById(R.id.friend);
        momentBtn = findViewById(R.id.moment);
        headImage = findViewById(R.id.headImage);
        drawerBtn = findViewById(R.id.drawerBtn);
        drawerLayout = findViewById(R.id.drawerLayout);
        profile_headImage = findViewById(R.id.profile_head);
        profile_NickName = findViewById(R.id.profile_nickName);
        profile_figure = findViewById(R.id.profile_figure);
        profile_logout = findViewById(R.id.profile_logout);
        nickName = findViewById(R.id.nickName);
        add_friend = findViewById(R.id.add_friend);
        publish_moment = findViewById(R.id.publish_moment);
        profile_about = findViewById(R.id.profile_about);
        profile_celar_cache = findViewById(R.id.profile_clear_cache);
    }

    private void setListeners() {

        //底部消息按钮的点击事件
        messageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchMessageFragment();
            }
        });

        //底部朋友按钮的点击事件
        friendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFriendFragment();
            }
        });

        //底部动态按钮的点击事件
        momentBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchMomentFragment();
            }
        });


        //汉堡按钮的点击事件
        drawerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "点击了汉堡按钮");
                drawerLayout.openDrawer(Gravity.RIGHT);
            }
        });

        //头像的点击事件
        headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.e(TAG, "点击了头像");
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });

        //汉堡按钮的监听事件
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                drawerView.setClickable(true); //去掉底层的焦点
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.LEFT);
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.LEFT);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        //抽屉头像的点击事件
        profile_headImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), UserinfoActivity.class);
                intent.putExtra("user_id", store.getCurrentUser().getUsername());
                startActivity(intent);
                drawerLayout.closeDrawer(Gravity.LEFT);
            }
        });

        //退出登录按钮点击事件
        profile_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                finish();
            }
        });

        //关于按钮点击事件
        profile_about.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), AboutActivity.class));
            }
        });

        //清楚缓存按钮的点击事件
        profile_celar_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String size = ImageUtil.getCacheSize(MainActivity.this);
                Log.e(TAG, "CacheSize : " + size);
                ImageUtil.clearImageAllCache(getApplicationContext());
                Toast.makeText(MainActivity.this,
                        "成功清理了 " + size,
                        Toast.LENGTH_SHORT).show();
            }
        });

        //添加好友按钮点击事件
        add_friend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), AddFriendActivity.class));
                drawerLayout.closeDrawer(Gravity.RIGHT);
            }
        });

        //发表动态按钮点击事件
        publish_moment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getApplicationContext(), PublishMomentActivity.class));
                drawerLayout.closeDrawer(Gravity.RIGHT);
            }
        });
    }

    private BroadcastReceiver clearCacheReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            ImageUtil.glideLoad(getApplicationContext(), store.getCurrentUser().getUsername(), store.cacheState, profile_headImage);
            ImageUtil.glideLoad(getApplicationContext(), store.getCurrentUser().getUsername(), store.cacheState, headImage);
            flush = true;
        }
    };

    private BroadcastReceiver updateUserReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            UserService.RESULT result = (UserService.RESULT) bundle.getSerializable("result");
            if (result == UserService.RESULT.SUCCESS) {
                User user = (User) bundle.getSerializable("user");
                nickName.setText(user.getNickName());
                profile_NickName.setText(user.getNickName());
                profile_figure.setText(user.getFigure());
            }
        }
    };
    private BroadcastReceiver netChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = manager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    if (!net_state) {
                        Log.e(TAG, "onReceive: " + "我连上往了");
                        net_state = true;
                        initClient();
                    }
                } else {
                    //断网了，改变网络状态
                    net_state = false;
                }
            }

        }
    };
}